package gui;

import org.eclipse.swt.SWT;
import org.eclipse.swt.SWTError;
import org.eclipse.swt.browser.Browser;
import org.eclipse.swt.layout.FillLayout;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Shell;

/**
 * Print HTML code by using the browser build-in printer functionality.
 *
 */
public class Printer {
	
	// No need to create instance of this class
	private Printer(){};
	
	/**
	 * Print HTML code.
	 * 
	 * @param title Title of the window and printed document
	 * @param contents HTML code to print (excluding <HTML>, <HEAD> and <BODY> tags)
	 * @return success
	 */
	public static boolean print(String title, String contents) {
		String html = "<HTML><HEAD><TITLE>" + title + "</TITLE></HEAD>";
		html += "<BODY>" + contents + "<SCRIPT language='javascript'>print();</script></BODY></HTML>";
		
		Display display = Display.getCurrent();
		Shell shell = new Shell(display);
		shell.setText(title);
		
		shell.setLayout(new FillLayout());
		Browser browser;
		try {
			browser = new Browser(shell, SWT.NONE);
		} catch (SWTError e) {
			System.out.println("Browser failed to start: " + e.getMessage());
			return false;
		}
		browser.setText(html);
		
		shell.open();
		while (!shell.isDisposed()) {
			if (!display.readAndDispatch())
				display.sleep();
		}
		shell.dispose();
		return true;
	}
}
